package com.influency.itlab.http.convert;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.influency.itlab.http.base.BaseResult;
import com.influency.itlab.http.base.ParameterizedTypeImpl;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody,T> {
    static String TAG = CustomGsonResponseBodyConverter.class.getSimpleName();
    private Gson gson;

    private Type type;
    private final TypeAdapter<T> adapter;
    public CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter,Type type) {
        this.gson = gson;
        this.adapter = adapter;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody response) throws IOException {
        String resultStr = response.string();
        Log.e(TAG,resultStr+"");


        try {
//            BaseResult baseResult = (BaseResult) adapter.fromJson(response.charStream());
            BaseResult<T> resultHolder = gson.fromJson(resultStr, getAssembleTypes(type));
            Log.e(TAG,resultHolder+"");
            if(resultHolder == null){
                throw new BaseResultException("invalid convert",-1);
            }
            T result = resultHolder.getResult();
            int resultCode = resultHolder.getStatus();
            String resultMsg = resultHolder.getMsg();
            if (!resultHolder.isSuccess()) {
                throw new BaseResultException(resultMsg,resultCode);
            }
            return result;
        }finally {
            response.close();
        }
    }

    protected Type getAssembleTypes(Type type){
        Type superType = getClass().getGenericSuperclass();
        Type[] parameterTypes = null;
        if (superType instanceof ParameterizedType){
            parameterTypes = ((ParameterizedType)superType).getActualTypeArguments();
        }else{
            parameterTypes = new Type[]{type};
        }
        Type assembleType = new ParameterizedTypeImpl(BaseResult.class,parameterTypes);
        return assembleType;
    }

}